import { UserAction } from "@/store/reducers/user";
// 引入发送请求的库
import http from "@/utils/request";
// 引入store中的数据类型
import { AppDispatch } from "@/store";
import { saveAuth, removeAuth } from "@/utils/storage";

// 导入 用户资料类型
import { Profile } from "@/store/reducers/user";
export const sendCodes = (mobile: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/sms/codes/${mobile}`);
    console.log("验证码返回");
    console.log(res);
    // dispatch 暂时用不到
  };
};

/**
 * 用户认证（登录注册）
 * @param {object} { mobile, code }
 * @returns
 */
export const loginAction = ({
  mobile,
  code,
}: {
  mobile: string;
  code: string;
}) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.post("/v1_0/authorizations", { mobile, code });
    // console.log(res);
    // 数据存放到 本地存储
    saveAuth(res.data);
    // 存一份到  redux中
    dispatch({ type: "user/saveAuth", payload: res.data });
  };
};

/**
 * 获取用户自己信息
 * @returns
 */
export const getUserInfo = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get("/v1_0/user");
    dispatch({ type: "user/saveUser", payload: res.data });
  };
};

/**
 * 获取用户个人资料
 */
export const getUserProfile = () => {
  return async (dispatch: AppDispatch) => {
    // 发送起请求
    const res = await http.get(`/v1_0/user/profile`);
    // 触发 reducer
    dispatch({ type: "user/saveProfile", payload: res.data });
  };
};

export const updatePhotoAction = (formData: FormData) => {
  return async () => {
    // 调用接口
    const res = await http({
      url: "/v1_0/user/photo",
      data: formData,
      method: "patch",
    });
    console.log(res);
  };
};

/**
 * 用户资料的编辑
 * @param profile 用户资料
 */
export const updateProfileAction = (profile: Partial<Profile>) => {
  return async () => {
    const res = await http({
      url: "/v1_0/user/profile",
      data: profile,
      method: "patch",
    });
    console.log(res);
  };
};

export const logoutAction = (): UserAction => {
  // 清除本地存储
  removeAuth();
  // 触发 reducer
  return {
    type: "user/clearAuth",
  };
};
